<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { ref } from 'vue'
	import { getLabel, getFutureDate } from '@/utils/common'
	import { getDicts } from '@/api/login'
	import { getOrderDetail, orderSubmit, orderCancel } from '@/api/purchase'
	
	const loading = ref(true)
	const type = ref('detail')
	const methodColumns = ref([])
	const uForm = ref(null)
	const form = ref({items: []})
	const rules = ref({
		payMethodIndex: [
			{type: 'number', required: true, message: '请选择结算方式', trigger: 'change'}
		],
		expectedTime: [
			{required: true, message: '请选择期望到货时间', trigger: ['blur', 'change']}
		]
	})
	const expectedTime = getFutureDate(0, '{y}-{m}-{d}')
	const cancelPopup = ref(null)
	
	function init(id) {
		getDicts('biz_purchase_pay_method').then(res => {
			methodColumns.value = res.result?.records || []
			getData(id)
		})
	}
	function getData(id) {
		loading.value = true
		getOrderDetail(id).then(res => {
			let data = res.result || {items: []}
			let findIndex = methodColumns.value.findIndex(item => item.value === data.payMethod)
			data.payMethodIndex = findIndex === -1? undefined : findIndex
			data.items.map((item, index) => {
				let name = 'price_' + index
				data[name] = item.price
				rules.value[name] =  [ {type: 'number', required: true, message: '请输入采购单价', trigger: 'change'} ]
			})
			form.value = data
			loading.value = false
		}).catch(() => loading.value = false)
	}
	function getDictLabel(key, value) {
		switch(key) {
			case 'payMethod': return getLabel(methodColumns.value, value);
			default: return ''
		}
	}
	function methodChange(e) {
		let index = e.detail.value
		form.value.payMethodIndex = index
		form.value.payMethod = methodColumns.value[index].value
		uForm.value.validateField('payMethodIndex')
	}
	function expectedChange(e) {
		let time = e.detail.value
		form.value.expectedTime = time
	}
	function goSubmit() {
		uForm.value.validate().then(() => {
			loading.value = true
			let params = uni.$uv.deepClone(form.value)
			delete params.payMethodIndex
			params.items.map((item, index) => {
				let name = 'price_' + index
				delete params[name]
			})
			orderSubmit(params).then(res => {
				uni.showToast({icon: 'success', title: '提交成功'})
				loading.value = false
				setTimeout(() => { uni.navigateBack() }, 200)
			}).catch(() => loading.value = false)
		})
	}
	function goCancle() {
		cancelPopup.value.open()
	}
	function closeCancel() {
		cancelPopup.value.close()
	}
	function confirmCancel() {
		loading.value = true
		let params = uni.$uv.deepClone(form.value)
		delete params.payMethodIndex
		params.items.map((item, index) => {
			let name = 'price_' + index
			delete params[name]
		})
		orderCancel(params).then(res => {
			uni.showToast({icon: 'success', title: '取消成功'})
			loading.value = false
			closeCancel()
			setTimeout(() => { uni.navigateBack() }, 200)
		}).catch(() => loading.value = false)
	}
	function goReturn() {
		uForm.value.validate().then(() => {
			loading.value = true
			let params = uni.$uv.deepClone(form.value)
			delete params.payMethodIndex
			params.items.map((item, index) => {
				let name = 'price_' + index
				delete params[name]
			})
			orderCancel(params).then(res => {
				uni.showToast({icon: 'success', title: '取消成功'})
				loading.value = false
				setTimeout(() => { uni.navigateBack() }, 200)
			}).catch(() => loading.value = false)
		})
	}
	
	onLoad((option) => {
		type.value = option.type || 'detail'
		let title = ''
		switch(type.value) {
			case 'submit': title = '提交订单'; break;
			case 'cancel': title = '取消订单'; break;
			case 'return': title = '退货'; break;
			default: title = '详情'; break;
		}
		uni.setNavigationBarTitle({title})
		if(option.id){
			init(option.id)
		}
	})
</script>

<template>
	<view :class="['app-container', ['submit', 'cancle', 'return'].includes(type)? 'show-bottom' : '']">
		<uv-form :model="form" :rules="rules" ref="uForm" labelWidth="210" :labelStyle="{color: '#6C6F73'}">
			<view class="form-box">
				<view class="head">基础信息</view>
				<view class="content">
					<uv-form-item label="采购单号">
						<view class="custom-content">
							<text>{{form.code || '--'}}</text>
						</view>
					</uv-form-item>
					<uv-form-item label="合单单号">
						<view class="custom-content">
							<text>{{form.mergeCode || '--'}}</text>
						</view>
					</uv-form-item>
					<uv-form-item label="采购人">
						<view class="custom-content">
							<text>{{form.contactName || '--'}}</text>
						</view>
					</uv-form-item>
					<uv-form-item label="供应商名称">
						<view class="custom-content">
							<text>{{form.supplierName || '--'}}</text>
						</view>
					</uv-form-item>
					<uv-form-item label="仓库地址">
						<view class="custom-content">
							<text>{{form.warehouseAddr || '--'}}</text>
						</view>
					</uv-form-item>
					<uv-form-item label="结算方式" prop="payMethodIndex" :required="type === 'submit'">
						<template v-if="type === 'submit'">
							<picker @change="methodChange" :value="form.payMethodIndex" :range="methodColumns" range-key="label">
								<view class="flex-justify">
									<text :class="form.payMethod? '' : 'text-no'">{{form.payMethod? getDictLabel('payMethod', form.payMethod) : '请选择'}}</text>
									<uv-icon name="arrow-right" color="#54504D" size="30" />
								</view>
							</picker>
						</template>
						<template v-else>
							<text>{{getDictLabel('payMethod', form.payMethod) || '--'}}</text>
						</template>
					</uv-form-item>
					<uv-form-item label="期望到货时间" prop="expectedTime" :required="type === 'submit'">
						<template v-if="type === 'submit'">
							<picker @change="expectedChange" mode="date" :start="expectedTime" :value="form.expectedTime">
								<view class="flex-justify">
									<text :class="form.expectedTime? '' : 'text-no'">{{form.expectedTime? form.expectedTime : '请选择'}}</text>
									<uv-icon name="arrow-right" color="#ADB0BD" size="30" />
								</view>
							</picker>
						</template>
						<template v-else>
							<text>{{form.expectedTime || '--'}}</text>
						</template>
					</uv-form-item>
					<uv-form-item label="订单备注">
						<view class="custom-content">
							<template v-if="type === 'submit'">
								<uv-input v-model="form.remarks" placeholder="请输入" border="none" maxlength="300" clearable />
							</template>
							<template v-else>
								<text>{{form.remarks || '--'}}</text>
							</template>
						</view>
					</uv-form-item>
				</view>
			</view>
			<view class="form-box" v-if="form.deliveryId">
				<view class="head">发货信息</view>
				<view class="content">
					<uv-form-item label="送货人">
						<view class="custom-content">
							<text>{{form.deliveryName || '--'}}</text>
						</view>
					</uv-form-item>
					<uv-form-item label="联系方式">
						<view class="custom-content">
							<text>{{form.deliveryPhone || '--'}}</text>
						</view>
					</uv-form-item>
					<uv-form-item label="送货时间">
						<view class="custom-content">
							<text>{{form.deliveryTime || '--'}}</text>
						</view>
					</uv-form-item>
				</view>
			</view>
			<view class="form-box">
				<view class="head">采购商品</view>
				<view class="content">
					<view class="list-box" v-for="(item, index) in form.items" :key="item.itemId">
						<view class="box-head">
							<text class="title">{{item.goodsName}}</text>
							<text class="num">采购量：{{item.demanded || 0}}</text>
						</view>
						<view class="box-info">
							<view class="box-row">
								<text class="label">商品规格：</text>
								<text class="value">{{item.goodsSpecs || '--'}}</text>
							</view>
							<view class="box-row">
								<text class="label">商品单位：</text>
								<text class="value">{{item.goodsUnit || '--'}}</text>
							</view>
						</view>
						<view class="box-info flex-align">
							<view class="box-row">
								<text class="label">商品单价：</text>
								<text class="value font-weight">￥{{item.goodsPrice? item.goodsPrice.toFixed(2) : 0.00}}</text>
							</view>
							<view class="box-row flex-align">
								<text class="label">采购单价：</text>
								<text class="text-required" v-if="type === 'submit'">*</text>
								<view class="value" v-if="type === 'submit'">
									<uv-form-item :prop="'price_' + index" labelWidth="0" >
										<view class="custom-content">
											<uv-input type="number" :custom-style="{background: '#FFF'}" v-model="form['price_' + index]" placeholder="请输入"
												maxlength="300" clearable />
										</view>
									</uv-form-item>
								</view>
								<text class="value" v-else>{{item.price}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</uv-form>
		<view class="form-bottom theme-btn" v-if="['submit', 'cancel', 'return'].includes(type)">
			<uv-button type="primary" shape="circle" text="提交" @click="goSubmit" :disabled="loading" v-if="type === 'submit'"></uv-button>
			<uv-button type="primary" shape="circle" text="取消订单" @click="goCancle" :disabled="loading" v-else-if="type === 'cancel'"></uv-button>
			<uv-button type="primary" shape="circle" text="退货" @click="goReturn" :disabled="loading" v-else></uv-button>
		</view>
		
		<uv-popup ref="cancelPopup" mode="center" round="32" :safeAreaInsetBottom="false">
			<view class="popup-box">
				<view class="popup-title">温馨提示</view>
				<view class="popup-content">采购单取消后无法恢复，是否确认取消采购订单？</view>
				<view class="popup-bottom">
					<uv-button shape="circle" :custom-style="{width: '296rpx'}" text="取消" @click="closeCancel"></uv-button>
					<uv-button type="primary" shape="circle" :custom-style="{width: '296rpx'}" text="确定" @click="confirmCancel"></uv-button>
				</view>
			</view>
		</uv-popup>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		padding-top: 2rpx;
		&.show-bottom{
			padding-bottom: 116rpx;
			padding-bottom: calc(constant(safe-area-inset-bottom) + 116rpx);
			padding-bottom: calc(env(safe-area-inset-bottom) + 116rpx);
		}
		.form-box{
			padding: 16rpx 32rpx;
			margin-bottom: 14rpx;
			background-color: #fff;
			.head{
				margin: 18rpx 0;
				position: relative;
				font-size: var(--theme-lg);
				font-weight: 600;
				&::before{
					content: "";
					position: absolute;
					top: 8rpx;
					left: -16rpx;
					width: 8rpx;
					height: 30rpx;
					background-color: $uv-primary;
				}
			}
			.content{
				.custom-content{
					width: 100%;
				}
				.flex-justify{
					display: flex;
					align-items: center;
					justify-content: space-between;
				}
				.text-no{
					color: #9CA0A6;
				}
				.text-required{
					color: #F82323;
					font-size: var(--theme-xxl);
				}
				::v-deep .uv-form-item__body{
					padding: 18rpx 0;
				}
				::v-deep .uv-form-item__body__left__content{
					flex: 0 0 auto;
				}
				::v-deep .uv-form-item__body__left__content__required{
					left: unset;
					right: -8rpx;
				}
			}
			.list-box{
				padding: 24rpx;
				background-color: #F5F7FA;
				border-radius: 8rpx;
				border: 2rpx solid #F5F5F5;
				.box-head{
					display: flex;
					justify-content: space-between;
					align-items: center;
					.title{
						font-weight: 600;
					}
					.num{
						font-size: var(--theme-sm);
						color: #9CA0A6;
					}
				}
				.box-info{
					margin-top: 16rpx;
					display: flex;
					gap: 16rpx;
					font-size: var(--theme-sm);
					.box-row{
						width: calc(50% - 8rpx);
						display: flex;
						.label{
							flex-shrink: 0;
							color: #6C6F73;
						}
						.value{
							flex: 1;
							::v-deep .uv-form-item__body{
								padding: 0;
							}
						}
					}
				}
			}
			.list-box + .list-box{
				margin-top: 16rpx;
			}
			.font-weight{
				font-weight: 600;
			}
			.flex-align{
				align-items: center;
			}
		}
		.form-bottom{
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			height: 116rpx;
			height: calc(constant(safe-area-inset-bottom) + 116rpx);
			height: calc(env(safe-area-inset-bottom) + 116rpx);
			padding: 16rpx 24rpx;
			padding-bottom: calc(constant(safe-area-inset-bottom) + 16rpx);
			padding-bottom: calc(env(safe-area-inset-bottom) + 16rpx);
			background-color: #FFFFFF;
			box-shadow: 0rpx -8rpx 8rpx 0rpx rgba(0,0,0,0.04);
			z-index: 100;
		}
		.popup-box{
			width: 686rpx;
			padding: 32rpx;
			.popup-title{
				font-weight: 600;
				font-size: var(--theme-xl);
				line-height: var(--theme-xl-line);
				text-align: center;
			}
			.popup-content{
				padding: 30rpx 48rpx 48rpx;
				color: #6C6F73;
				text-align: center;
			}
			.popup-bottom{
				display: flex;
				justify-content: center;
				align-items: center;
				gap: 32rpx;
			}
		}
	}
</style>